package org.example.corpus.corpuscenter.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.example.corpus.config.Constants;
import org.example.corpus.corpuscenter.dao.CorpusDao;
import org.example.corpus.corpuscenter.service.CorpusService;
import org.example.corpus.corpuscenter.service.SentenceService;
import org.example.corpus.model.Corpus;
import org.example.corpus.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import java.io.*;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.IOException;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;

@Slf4j
@Service
public class CorpusServiceImpl implements CorpusService {
    @Autowired
    private CorpusDao corpusDao;
    @Autowired
    private SentenceService sentenceService;

    @Override
    public List<Corpus> getCorpusList(int offset, int pageSize, String keyword, Boolean isUser) {
        if(isUser==true){
            return corpusDao.getUserCorpusList(offset, pageSize, keyword,(Integer) ThreadLocalUtil.getOne("id"));
        }
        return corpusDao.getCorpusList(offset, pageSize, keyword);
    }

    @Override
    public Integer createCorpus(String name, String description, MultipartFile file) {
        Corpus corpus = new Corpus();
        String fullFileName = file.getOriginalFilename();
        String fileName="";
        String extension = "";
        if (fullFileName.contains(".")) {
            fileName = name;
            extension = fullFileName.substring(fullFileName.lastIndexOf(".")+1);
        }
        corpus.setUserId((Integer) ThreadLocalUtil.getOne("id"));
        corpus.setName(fileName);
        corpus.setDescription(description);
        String filePath = saveCorpus(fileName, extension, (Integer) ThreadLocalUtil.getOne("id"));
        corpus.setFilePath(filePath);
        corpus.setFileType(extension);
        // 设置创建时间和更新时间为当前时间
        Date now = new Date();
        corpus.setCreatedAt(now);
        corpus.setUpdatedAt(now);
        File dest = new File(filePath);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 插入数据库
        Integer ret = corpusDao.insertCorpus(corpus);
        int corpusId = corpus.getId();
        sentenceService.processFile(filePath,corpusId);
        // 返回插入后的对象
        return ret;
    }

    @Override
    public List<Corpus> selectCorpusList(String keyword) {
        List<Corpus> corpora = corpusDao.selectCorpus(keyword);
        return corpora;
    }


    @Override
    public Resource downloadCorpus(int corpusId) {
        Corpus corpus = corpusDao.selectCorpusById(corpusId);
        if (corpus == null) {
            return null;  // 如果没有找到对应的Corpus，返回null
        }
        String fileNameToSearch = corpus.getName() + "." + corpus.getFileType();
        System.out.println(fileNameToSearch);
        Path folder = Paths.get(Constants.CORPUS_PATH+ThreadLocalUtil.getOne("id"));  // 要搜索的目录路径

        try {
            List<Path> foundFiles = searchFilesByName(folder, fileNameToSearch);
            if (foundFiles.isEmpty()) {
                return null;
            } else {
                for (Path file : foundFiles) {
                    return loadFileAsResource(file);  // 找到第一个文件后立即返回
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static List<Path> searchFilesByName(Path folder, String fileName) throws IOException {
        List<Path> result = new ArrayList<>();

        // 使用 Files.walk 来遍历目录下的所有文件
        Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // 如果文件名匹配，则将文件路径添加到结果列表
                if (file.getFileName().toString().equalsIgnoreCase(fileName)) {
                    result.add(file);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                // 如果访问某个文件失败，继续遍历
                return FileVisitResult.CONTINUE;
            }
        });

        return result;
    }

    private Resource loadFileAsResource(Path filePath) throws IOException {
        File file = filePath.toFile();
        InputStream inputStream = new FileInputStream(file);
        return new InputStreamResource(inputStream);  // 将文件内容包装为 InputStreamResource
    }

    private String saveCorpus(String fileName,String extension,Integer userId) {//获取文件路径
        // 定义静态资源路径
        String staticPath = Constants.CORPUS_PATH;

        // 创建以用户ID为目录的路径
        String userDir = staticPath + userId;

        // 如果用户目录不存在，创建该目录
        File userDirFile = new File(userDir);
        if (!userDirFile.exists()) {
            userDirFile.mkdirs();  // 创建目录
        }

        // 拼接完整的文件路径
        String filePath = userDir + "/" + fileName +  "." + extension;
        return filePath;
    }

    @Override
    public Corpus getCorpusById(int CorpusId) {
        return corpusDao.selectCorpusById(CorpusId);
    }

    @Override
    public String getCorpusNameById(int CorpusId) {
        Corpus corpus = corpusDao.selectCorpusById(CorpusId);
        if (corpus == null) {
            return null;  // 如果没有找到对应的Corpus，返回null
        }
        return corpus.getName()+"."+corpus.getFileType();
    }
}
